﻿module Sustainalytics.GCCS {

    import Company = Sustainalytics.Company;
    import LRTM = Sustainalytics.LRTM;

    export class GCCompanyController {

        // current company
        public companyNameQueryString: string;
        public company: Company.CorporateDataExtendedDto;

        // current overall assessment
        public overallAssessment: GCAssessment;

        // current overall company summary
        public overallCompanySummary: GCOverallCompanySummaryDto;

        // company principles
        public companyPrinciples: GCPrincipleSummaryDto[];

        // company principles count by NC or WL
        public companyPrinciplesNcCount: number;
        public companyPrinciplesWlCount: number;

        // permissions
        public gcPermissions: GCCS.Security.GCPermissions;

        // whether current company is in the NC universe of company
        public hasNcUniverse: boolean;

        // whether current company is in the WL universe of company
        public hasWlUniverse: boolean;

        // whether an error occured during init
        public isInitError: boolean = false;

        // wther init is running
        public isInitLoading: boolean = true;

        // whether the company does not have GC data
        public isGcNotFound: boolean = false;

        public hasFrameworkNotApplicable: boolean;

        public isGccsCompliant() : boolean {
            return this.overallCompanySummary && this.overallCompanySummary.overallCompanyAssessment === 0;
        }

        public $routeParams: any;

        private userId: string;
        private accountId: string;

        constructor(
            private $rootScope: ng.IScope,
            public $scope: ng.IScope,
            private $q: ng.IQService,
            private GCOverallCompanySummaryService: IGCOverallCompanySummaryService,
            private GCPrincipleSummaryService: IGCPrincipleSummaryService,
            private $location: ng.ILocationService,
            private RoutingService: Routing.IRoutingService,
            private CompanyService: Company.ICompanyService,
            private GCPermissionsService: GCCS.Security.IGCPermissionsService,
            private LongRunningTaskManagerService: LRTM.LongRunningTaskManagerService) {

            var ctx = this;
            ctx.$routeParams = ctx.RoutingService.getRouteParams();
            ctx.$scope['gcCompany'] = ctx;

            // set default overall assessment
            this.overallAssessment = null;

            var initPromise = this.init();

            initPromise.then(function () {
                // watch for overall assessment changes
                ctx.$scope.$watch('gcCompany.overallAssessment', function (newVal, oldVal, scope) {

                });
            });

            if (ctx.$rootScope['userInfo'] == null) {
                ctx.$rootScope['userInfo'] = angular.fromJson(localStorage.getItem('sust_userInfo'));
            }
            ctx.userId = ctx.$rootScope['userInfo'].userId;
            ctx.accountId = ctx.$rootScope['userInfo'].accountId;
        }

        init(): ng.IPromise<any> {
            var ctx = this;

            ctx.isInitLoading = true;

            // get company name from route params
            var companyName: string = ctx.$routeParams['companyName'];
            ctx.companyNameQueryString = companyName;

            // get company by name
            var companyPromise = ctx.CompanyService.getByNameUrlFriendly(companyName);

            var def = ctx.$q.defer();

            // get permissions
            ctx.gcPermissions = ctx.GCPermissionsService.getPermissions();

            if (!ctx.gcPermissions.hasNC && !ctx.gcPermissions.hasWL) {

                // redirect to Overview tab
                this.$location.path('/research/' + ctx.companyNameQueryString);

                def.reject();
                return def.promise;
            }

            // set default selected tab
            ctx.init_defaultSelectedTab();

            // get overall assessment from route params
            var overallAssessmentUrlName: string = ctx.$routeParams['overallAssessment'];
            var overallAssessmentFromUrl = GCUtility.getGcAssessmentFromUrlName(overallAssessmentUrlName);
            if (overallAssessmentFromUrl)
                ctx.overallAssessment = overallAssessmentFromUrl;


            // after obtaining the company info get also other related info
            companyPromise
                .success(function (company) {
                    ctx.company = company;

                    // get has NC universe
                    var hasNcUniversePromise = ctx.getHasNcUniverse(company.id);

                    // get has WL universe
                    var hasWlUniversePromise = ctx.getHasWlUniverse(company.id);

                    ctx.hasFrameworkNotApplicable = (company.gccsResearchState == Company.ResearchState.FrameworkNotApplicable);

                    ctx.$q.all([hasNcUniversePromise, hasWlUniversePromise])
                        ['finally'](function () {

                            // get overall company summary
                            var overallInfoPromise = ctx.getOverallCompanySummary();

                            overallInfoPromise.then(
                                // success
                                function () {
                                    // get company principles
                                    var principlesPromise = ctx.getCompanyPrinciples();

                                    // get principles WL/NC count
                                    var principlesCountPromise = ctx.getCompanyPrinciplesCount();

                                    ctx.$q.all([ principlesPromise, principlesCountPromise ]).then(
                                        // success
                                        function () {
                                            def.resolve();
                                        },
                                        // error
                                        function (reason) {
                                            def.reject(reason);
                                        });
                                },
                                // error
                                function (reason) {
                                    ctx.isInitError = true;
                                    def.reject(reason);
                                });
                        });
                })
                ['catch'](function () {
                    def.reject();
                });

            var promise = def.promise;

            promise['finally'](function () {
                ctx.isInitLoading = false;

                if (ctx.company != undefined) {
                    ga('create', 'UA-4379897-6', {
                        'userId': ctx.userId,
                        'cookieDomain': 'none',
                        'name': 'globalAccess'
                    });

                    ga('globalAccess.set', 'dimension1', ctx.userId);

                    var dateNow = new Date();
                    var dateNowString = [dateNow.getDate(), dateNow.getMonth() + 1, dateNow.getFullYear()].join("/");
                    var gaObject: any = {
                        Date: dateNowString,
                        AccountId: ctx.accountId,
                        UserId: ctx.userId,
                        CompanyId: ctx.company.id
                    };

                    ga('globalAccess.send', {
                        'hitType': 'event',
                        'eventCategory': 'Research',
                        'eventAction': 'OnscreenGlobalCompactReport',
                        'eventLabel': JSON.stringify(gaObject)
                    });
                }
            });

            return promise;
        }

        private setOverallAssessment(overallAssessment: GCAssessment): void {
            var ctx = this;
            var oldAssessment = ctx.overallAssessment;

            if (oldAssessment !== overallAssessment) {
                ctx.overallAssessment = overallAssessment;
                // get company principles
                var principlesPromise = ctx.getCompanyPrinciples();
            }
        }

        // get whether current company is in the NC universe of company
        private getHasNcUniverse(companyId): ng.IPromise<boolean> {
            var ctx = this;
            var def = ctx.$q.defer();

            ctx.GCOverallCompanySummaryService.GetByCompany(companyId, GCAssessment.NonCompliant)
                .then(
                function (company: GCOverallCompanySummaryDto) {
                    ctx.hasNcUniverse = true;
                    def.resolve(company);
                },
                function (reason) {
                    if (reason.status !== 404 && reason.status !== 401) {
                        ctx.isInitError = true;
                    }

                    def.reject(reason);
                });

            return def.promise;
        }

        // get whether current company is in the WL universe of company
        private getHasWlUniverse(companyId): ng.IPromise<any> {
            var ctx = this;
            var def = ctx.$q.defer();

            ctx.GCOverallCompanySummaryService.GetByCompany(companyId, GCAssessment.Watchlist)
                .then(
                function (company: GCOverallCompanySummaryDto) {
                    ctx.hasWlUniverse = true;
                    def.resolve(company);
                },
                function (reason) {
                    if (reason.status !== 404 && reason.status !== 401) {
                        ctx.isInitError = true;
                    }

                    def.reject(reason);
                });

            return def.promise;
        }

        init_defaultSelectedTab() {
            var ctx = this;

            // set default selected tab
            if (ctx.gcPermissions.hasNC) {
                ctx.overallAssessment = GCAssessment.NonCompliant;
            }
            else {
                if (ctx.gcPermissions.hasWL) {
                    ctx.overallAssessment = GCAssessment.Watchlist;
                }
            }
        }

        private onOverallAssessmentChanged() {
        }

        // get overall company summary
        getOverallCompanySummary(): ng.IPromise<GCOverallCompanySummaryDto> {
            var ctx = this;

            ctx.overallCompanySummary = null;

            // get overall company summary
            var promise = ctx.GCOverallCompanySummaryService.GetByCompany(ctx.company.id, null);

            promise.then(
                // success
                function (data) {
                    ctx.overallCompanySummary = data;
                },
                // error
                function (reason) {

                    // if no GC data was found
                    if(reason.status === 404) {
                        ctx.isGcNotFound = true;
                    }
                });

            return promise;
        }

        // get company principles
        public getCompanyPrinciples(): ng.IPromise<GCPrincipleSummaryDto[]> {
            var ctx = this;

            var companyId = ctx.company.id;

            if (!companyId) {
                var p: any = ctx.$q.reject();
                return p;
            }

            if ((ctx.overallAssessment == GCAssessment.NonCompliant && !ctx.hasNcUniverse)
                || (ctx.overallAssessment == GCAssessment.Watchlist && !ctx.hasWlUniverse)) {
                var p: any = ctx.$q.reject();
                return p;
            }

            // get company principles
            var promise: ng.IPromise<GCPrincipleSummaryDto[]> = ctx.GCPrincipleSummaryService.getList(companyId, ctx.overallAssessment);

            promise.then(function (data) {
                ctx.companyPrinciples = data;
            });

            return promise;
        }

        // get NC and WL principles count
        public getCompanyPrinciplesCount(): ng.IPromise<any> {
            var ctx = this;

            var companyId = ctx.company.id;

            if (!companyId) {
                var p: any = ctx.$q.reject();
                return p;
            }

            if ((ctx.overallAssessment == GCAssessment.NonCompliant && !ctx.hasNcUniverse)
                || (ctx.overallAssessment == GCAssessment.Watchlist && !ctx.hasWlUniverse)) {
                var p: any = ctx.$q.reject();
                return p;
            }

            var promiseNc = ctx.GCPrincipleSummaryService.getCount(companyId, GCAssessment.NonCompliant);

            promiseNc.then(function (count) {
                ctx.companyPrinciplesNcCount = count;
            });

            var promiseWl = ctx.GCPrincipleSummaryService.getCount(companyId, GCAssessment.Watchlist);

            promiseWl.then(function (count) {
                ctx.companyPrinciplesWlCount = count;
            });

            return ctx.$q.all([ promiseNc, promiseWl ]);
        }

        public showNcUniverseWarning(): boolean {
            return !this.hasNcUniverse && this.overallAssessment == GCAssessment.NonCompliant;
        }

        public showWlUniverseWarning(): boolean {
            return !this.hasWlUniverse && this.overallAssessment == GCAssessment.Watchlist;
        }

        public showDownloadPdfExport(): boolean {
            var ctx = this;

            switch (ctx.overallAssessment) {
                case GCAssessment.Watchlist:
                    return ctx.hasWlUniverse && ctx.gcPermissions.hasWL && ctx.companyPrinciples && ctx.companyPrinciples.length > 0;
                case GCAssessment.NonCompliant:
                    return ctx.hasNcUniverse && ctx.gcPermissions.hasNC && ctx.companyPrinciples && ctx.companyPrinciples.length > 0;
            }

            return false;
        }

        // download PDF export
        public downloadPdfExport(): ng.IPromise<any> {
            var ctx = this;

            if (!ctx.showDownloadPdfExport())
                return;

            var data: GccsPdfExportTaskParams =
                {
                    companyId: ctx.company.id,
                    overallAssessment: ctx.overallAssessment
                };

            var promise = ctx.LongRunningTaskManagerService.runTask('File', JSON.stringify(data), LRTM.LongRunningTaskTypeEnum.GccsReportPdf, true, null);

            ga('create', 'UA-4379897-6', {
                'userId': ctx.userId, 'cookieDomain': 'none', 'name': 'globalAccess'
            });

            ga('globalAccess.set', 'dimension1', ctx.userId);

            var dateNow = new Date();
            var dateNowString = [dateNow.getDate(), dateNow.getMonth() + 1, dateNow.getFullYear()].join("/");
            var gaObject: any = {
                Date: dateNowString,
                AccountId: ctx.accountId,
                UserId: ctx.userId,
                CompanyId: ctx.company.id
            };

            ga('globalAccess.send', {
                'hitType': 'event', 'eventCategory': 'Research', 'eventAction': 'PDFGlobalCompactReport', 'eventLabel': JSON.stringify(gaObject)
            });

            return promise;
        }

        public goToMultiCompanyList(overallAssessment: GCAssessment) {
            var ctx = this;

            var overallAssessmentQuery = '';
            switch (overallAssessment) {
                case GCAssessment.NonCompliant:
                    overallAssessmentQuery = '/NonCompliant';
                    break;
                case GCAssessment.Watchlist:
                    overallAssessmentQuery = '/Watchlist';
                    break;
            }

            ctx.$location.url('/research/globalcompact' + overallAssessmentQuery);
        }

        public initialLowercase(str: string): string {
            var ctx = this;

            // initial character to lowercase
            if (str && str.length > 0) {
                str = str.slice(0, 1).toLowerCase() + str.slice(1, str.length);
            }

            return str;
        }

        //public showCompanyControls(): boolean {
        //    var ctx = this;

        //    return !this.isInitError && (this.gcPermissions.hasNC || this.gcPermissions.hasWL) && this.overallCompanySummary !== null;
        //}
    }


    angular.module('Sustainalytics.GCCS').controller('GCCompanyController',
        ['$rootScope','$scope', '$q', 'GCOverallCompanySummaryService', 'GCPrincipleSummaryService', '$location', 'RoutingService', 'CompanyService',
            'GCPermissionsService', 'LongRunningTaskManagerService', GCCompanyController]);
}